
package com.hlkj.pay.app.merchant.ext.impl.helipay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.http.template.OkHttpTemplate;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.HeliPayEatrxConfig;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.eatrx.HeliPayEatrxAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.helipay.util.Des3;
import com.hlkj.pay.app.merchant.ext.impl.helipay.util.Disguiser;
import com.hlkj.pay.common.PayResultCode;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;

import lombok.extern.slf4j.Slf4j;

/**
 * 汇付 商户进件参数处理
 * 
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
@Service
public class HeliPayMerchantEatrxCommonParamsHandle<T> {

    @Autowired
    private OkHttpTemplate okHttpTemplate;

    @Value("${spring.profiles.active}")
    private String active;

    public String subject(String subject) throws UnsupportedEncodingException {
        return URLEncoder.encode(subject, "GBK");
    }

    public HeliPayEatrxAppChannelParams heePayAppChannelParams(MerchantAppChannelDO merchantAppChannelDO) {
        return JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), HeliPayEatrxAppChannelParams.class);
    }

    public CommonResult<HeliPayEatrxConfig> heliPayEatrxConfig(ProviderChannelConfigDO providerChannelConfigDO, boolean test) {
        String paramsConfig = providerChannelConfigDO.getParamsConfig();
        if (StringUtils.isEmpty(paramsConfig)) {
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS);
        }
        // 配置转换
        HeliPayEatrxConfig heePayConfig = null;
        try {
            heePayConfig = JsonUtils.parseObject(paramsConfig, HeliPayEatrxConfig.class);
            return CommonResult.success(heePayConfig);
        }
        catch (Exception e) {
            String format = String.format(PayResultCode.PAY_CHANNEL_CONFIG_ERROR.getMsg(), "合利宝");
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS.getCode(), format);
        }
    }

    /**
     * 通用请求
     * 
     * @param object
     * @param requestUrl
     * @return
     * @throws Exception
     */
    public CommonResult<T> productRequest(Object object, String requestUrl, Class<T> a, HeliPayEatrxConfig heePayConfig) {
        return commonRequest(object,requestUrl,a,heePayConfig.getMerchantNo(),heePayConfig.getProductDes3Key(),heePayConfig.getProductPrivateKey());
    }
    /**
     * 通用请求
     *
     * @param object
     * @param requestUrl
     * @return
     * @throws Exception
     */
    public CommonResult<T> commonRequest(Object object, String requestUrl, Class<T> a, String merchantNo,String des3Key ,String privateKey) {
        String result;
        try {
            Map<String, Object> map = new HashMap<>();
            // 加密
            String data = Des3.encode(des3Key, JsonUtils.toJsonString(object));
            // 加签
            String source = merchantNo + "&" + data + "&" + privateKey;
            String sign = Disguiser.disguiseSha256(source);
            map.put("data", data);
            map.put("sign", sign);
            map.put("merchantNo", merchantNo);
            map.put("signType", "SHA256");
            // 发送
            log.info("合利宝电子账户 通用请求参数:{}", JsonUtils.toJsonString(object));
            result = okHttpTemplate.post(requestUrl, JsonUtils.toJsonString(map), null);
            // 响应
            log.info("合利宝电子账户 解密前通用返回参数:{}", result);

            Map<String, String> resultObject = JsonUtils.parseObject(result, Map.class);
            String code = resultObject.get("code");
            if (!"0000".equals(code)) {
                return CommonResult.error(1, resultObject.get("message"));
            }
            String resMerchant = resultObject.get("merchantNo");
            String resData = resultObject.get("data");
            String resSign = resultObject.get("sign");
            String decode = Des3.decode(des3Key, resData);
            log.info("合利宝电子账户 解密后通用返回参数:{}", decode);
            return CommonResult.success(JsonUtils.parseObject(decode, a));
        }
        catch (Exception e) {
            return CommonResult.error(1, e.getMessage());
        }
    }

    /**
     * 通用请求
     *
     * @param object
     * @param requestUrl
     * @return
     * @throws Exception
     */
    public CommonResult<T> transferRequest(Object object, String requestUrl, Class<T> a, HeliPayEatrxConfig heePayConfig) {
        return commonRequest(object,requestUrl,a,heePayConfig.getMerchantNo(),heePayConfig.getTransferDes3Key(),heePayConfig.getTransferPrivateKey());
    }

    /**
     * 通用请求
     *
     * @param object
     * @param requestUrl
     * @return
     * @throws Exception
     */
    public CommonResult<T> withdrawRequest(Object object, String requestUrl, Class<T> a, HeliPayEatrxConfig heePayConfig) {
        return commonRequest(object,requestUrl,a,heePayConfig.getMerchantNo(),heePayConfig.getWithdrawDes3Key(),heePayConfig.getWithdrawPrivateKey());
    }

    public String url(boolean test) {
        if (test) {
            return "http://qa-shouyin.helipay.com/eatrx";
        }
        return "https://neo-ea.trx.helipay.com/eatrx";
    }

    public static String date(String date) {
        if (!StringUtils.hasText(date)) {
            return null;
        }
        return date.replaceAll("-", "");
    }

    public static String dateEnd(Integer licenseValidityType, String date) {
        if (CommonEnum.YES_NO_TYPE.YES.getCode().equals(licenseValidityType)) {
            return "20991231";
        }
        if (!StringUtils.hasText(date)) {
            return null;
        }
        return date.replaceAll("-", "");
    }

}
